<?php
namespace App\Http\Controllers\ApiXcx;

use App\Service\ApiXcx\PostService as Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends BaseController
{
    //贴子
    protected $fieldMsgs = [
        'type' => ['en' => 'type', 'cn' => '类型', 'ismust' => true],
        'title' => ['en' => 'title', 'cn' => '标题', 'ismust' => true],
        'content' => ['en' => 'content', 'cn' => '内容', 'ismust' => true],
        'cate_id' => ['en' => 'cate_id', 'cn' => '分类'],
        'images' => ['en' => 'images', 'cn' => '图片'],
    ];

    public function __construct()
    {
        $this->db = new Post();
    }

    //列表
    public function getList(Request $request)
    {
        $pages['start'] = $request->post('page', 1);
        $pages['limit'] = $request->post('size', 4);
        $type = $request->post('type', 0);
        $uid = $request->post('uid', 0);
        $res = $this->db->getList($pages, $type, $uid);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //详情
    public function getOne(Request $request)
    {
        $id = $request->post('id', 0);
        $res = $this->db->getOne($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //分类列表
    public function getCateList()
    {
        $res = $this->db->getCateList();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    public function add(Request $request){
        $validate = $this->checkField($request, $this->fieldMsgs);
        if ($validate['code'] < 0) {
            return $this->toJson(-2, $validate['msg']);
        }
        if($validate['data']['type'] == 1 && empty($validate['data']['cate_id'])) {
            return $this->toJson(-2, '活动话题分类必须');
        }
        $token = $request->post('token', '');
        $uid = $this->db->addApiCount($token);
        if (!$uid) {
            return $this->toJson(-2, '未登录');
        }
        $res = $this->db->add($validate['data'], $uid);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '添加成功');
    }
}